<script setup>
import { ref } from 'vue'
// import { ref, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import api from '@/api'
import { Message } from '@arco-design/web-vue'
const $route = useRoute()
const $router = useRouter()

const section = ref(null)

const plan_id = $route.query.plan_id
const isopen = ref(false)
const isHighLight = ref(false)

const goBack = () => {
  $router.go(-1)
}

const userLists = ref([])
const chooseUserId = ref('')

const chooseUsers = ref([])
const chooseUserIds = ref([])
const userCompareList = ref([])

const convertUserToCompare = (users) => {
  if (!users || users.length === 0) return []
  const resultMap = new Map()

  users.forEach((user) => {
    let total = 0
    user.content.forEach((plate) => {
      if (!resultMap.has(plate.plate_name)) {
        resultMap.set(plate.plate_name, {})
      }
      plate.son.forEach((problem) => {
        total += problem.score
        if (!resultMap.get(plate.plate_name)[problem.title]) {
          resultMap.get(plate.plate_name)[problem.title] = []
        }
        resultMap.get(plate.plate_name)[problem.title].push({
          answer: problem.answer,
          score: problem.score,
        })
      })
    })
    user.total_score = total
  })

  const results = []
  resultMap.forEach((problems, plate_name) => {
    const sonArray = Object.keys(problems).map((title) => ({
      title,
      results: problems[title],
    }))
    results.push({
      plate_name,
      son: sonArray,
    })
  })

  // 补全缺失问题答案和分数
  results.forEach((result) => {
    const usersLength = users.length
    result.son.forEach((problem) => {
      while (problem.results.length < usersLength) {
        problem.results.push({
          answer: '',
          score: '',
        })
      }
    })
  })

  return results
}

const removeUser = (index) => {
  chooseUserIds.value.splice(index, 1)
  console.log(chooseUsers.value)

  getUserInfo()
}

const activeIndex = ref('')

const handleChangeUser = (value) => {
  console.log('选择人员', value)
  let userId = value
  chooseUserId.value = '' // 选择人员后清空选择框
  chooseUserIds.value.push(userId)
  // 去重
  chooseUserIds.value = [...new Set(chooseUserIds.value)]
  getUserInfo()
}

const getUserInfo = async () => {
  // chooseUserIds.value = [1, 2]
  const res = await api.get(
    `/recruit/talentContrast?worker_id=${chooseUserIds.value.join(',')}`
  )
  chooseUsers.value = res.data
  if (chooseUsers.value.length < 2) {
    isHighLight.value = false
  }
  // 比对结果
  userCompareList.value = convertUserToCompare(res.data) || []
  // if (userCompareList.value.length > 0) {
  // 	activeIndex.value = userCompareList.value[0].plate_name;
  // }
  console.log('比对结果', userCompareList.value)
}

const getUserLists = async () => {
  let url = `/recruit/talentPoolAllList`;
  if ($route.query.plan_id) {
    url += `?recuit_plan_id=${$route.query.plan_id}`
  }
  const res = await api.get(url)
  userLists.value = res.data
}

const changeHighLight = () => {
  console.log(chooseUsers.value)
  if (chooseUsers.value.length < 2) {
    isHighLight.value = false
    return Message.error('请至少选择2名人员')
  }
}
const highLight = (results) => {
  // 假设数组不为空且至少有一个元素
  if (results.length === 0) return true // 或者根据你的需求，可能应该返回false

  // 取出第一个元素的score作为基准
  const firstScore = results[0].score

  // 使用every方法检查所有元素的score是否都与第一个相同
  let isSame = results.every((item) => item.score === firstScore)
  if (isHighLight.value == 1 && !isSame) {
    return 'background: #FFF6E1;'
  } else {
    return ''
  }
}
getUserLists()

function scrollToSection(index) {
  const element = document.getElementById(index)
  console.log(index)
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' })
  }
}
</script>

<template>
  <div class="page">
    <div class="header">
      <div>人才对比</div>
      <img
        @click="goBack"
        class="icon_close"
        src="@/assets/icons/close.png"
        alt=""
      />
    </div>

    <div
      class="weidu_icon"
      v-if="userCompareList.length > 0"
      @click="isopen = !isopen"
    >
      <img src="@/assets/icons/weidu.png" alt="" />
      <div>维度</div>
    </div>
    <div class="menu_cells" v-if="isopen">
      <div
        :class="activeIndex == '' ? 'item active' : 'item'"
        @click="activeIndex = ''"
      >
        <a @click="scrollToSection('zongfen')">总分数</a>
      </div>
      <div
        v-for="(item, index) in userCompareList"
        :key="index"
        :class="activeIndex == item.plate_name ? 'item active' : 'item'"
        @click="activeIndex = item.plate_name"
      >
        <!-- <a :href="'/#weidu' + index">{{ item.plate_name }}</a> -->

        <a @click="scrollToSection('weidu' + index)">{{ item.plate_name }}</a>
      </div>
    </div>
    <div class="contrast_body">
      <div class="card_cells" id="zongfen">
        <div class="card_cell">
          <div class="card_head">
            <div class="flex fd_c w100">
              <div class="mb10">共{{ chooseUsers.length }}名人员</div>
              <div>
                <a-checkbox v-model="isHighLight" @change="changeHighLight"
                  >高亮不同分数</a-checkbox
                >
              </div>
            </div>
          </div>
          <div class="card_body">总分数</div>
        </div>

        <div
          v-for="(item, index) in chooseUsers"
          :key="index"
          class="card_cell"
        >
          <div class="card_head">
            <icon-close class="card_close" @click="removeUser(index)" />
            {{ item.name }}
          </div>
          <div class="card_body" style="color: #005bac; font-weight: 600">
            {{ item.total_score }}
          </div>
        </div>

        <div class="card_cell">
          <div class="card_head">
            <a-select
              placeholder="新增人员"
              v-model="chooseUserId"
              allow-clear
              allow-search
              @change="handleChangeUser"
            >
              <a-option
                v-for="(item, index) in userLists"
                :key="index"
                :value="item.application_worker_id"
                >{{ item.worker_name }}</a-option
              >
            </a-select>
          </div>
          <div class="card_body"></div>
        </div>
      </div>

      <!-- <a-anchor line-less style="width: 100%; overflow: hidden;"> -->
      <div
        v-for="(item, index) in userCompareList"
        :key="index"
        :id="'weidu' + index"
      >
        <div class="block_title">{{ item.plate_name }}</div>

        <div class="info_header">
          <div class="info_block">问题</div>
          <div
            v-for="(item, index) in chooseUsers"
            :key="index"
            class="info_block1"
          >
            <div>回答</div>
            <div>分数</div>
          </div>
          <div class="info_block1">
            <div></div>
            <div></div>
          </div>
        </div>
        <div class="info_body" v-for="(item2, index) in item.son" :key="index">
          <div class="info_block" :style="highLight(item2.results)">
            <!-- <a-anchor-link :href="item2.title"> -->
            {{ item2.title }}
            <!-- </a-anchor-link> -->
          </div>

          <div
            v-for="(item3, indexs) in item2.results"
            :key="indexs"
            class="info_block1"
            :style="highLight(item2.results)"
          >
            <div>{{ item3.answer }}</div>
            <div>{{ item3.score }}</div>
          </div>

          <div class="info_block1">
            <div></div>
            <div></div>
          </div>
        </div>
      </div>
      <!-- </a-anchor> -->
    </div>
  </div>
</template>

<style scoped>
.page {
  position: relative;
  height: 95%;
  border-bottom: 0;
  background-color: #f2f4fa;
}

.header {
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #005bac;
  font-size: 16px;
  color: #fff;
  box-sizing: border-box;
  padding: 0 24px;
}

.icon_close {
  width: 22px;
  height: 22px;
  display: block;
  cursor: pointer;
}

.weidu_icon {
  position: fixed;
  top: 200px;
  left: 200px;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 0 5px 5px 0;
  box-shadow: #cacaca 0px 0px 2px 1px;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
  font-size: 10px;
  cursor: pointer;
}

.weidu_icon img {
  width: 16px;
  height: 16px;
  display: block;
  margin-bottom: 5px;
}

.menu_cells {
  box-shadow: #cacaca 0px 0px 2px 1px;
  border-radius: 0 6px 6px 0;
  position: fixed;
  top: 250px;
  left: 200px;
  width: 100px;
  font-size: 12px;
  background-color: #fff;
  box-sizing: border-box;
  padding: 5px;
}

.menu_cells > div {
  box-sizing: border-box;
  padding: 5px 12px;
  border-radius: 6px;
}

.menu_cells .active {
  background-color: #005bac;
  color: #fff;
}

.menu_cells .item > a {
  color: #000;
  text-decoration: none;
}

.menu_cells .active > a {
  color: #fff;
  text-decoration: none;
}

.contrast_body {
  box-sizing: border-box;
  padding: 24px;
  overflow-x: auto;
}

.card_cells {
  display: flex;
  align-items: center;
}

.card_cells > div {
  margin-right: 5px;
  border: 1px solid #e5e6eb;
  box-sizing: border-box;
}

.card_cell {
  width: 300px;
  flex-shrink: 0;
  background-color: #fff;
}

.card_head {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 64px;
  border-bottom: 1px solid #e5e6eb;
  box-sizing: border-box;
  padding: 20px;
  position: relative;
  font-size: 16px;
}

.card_close {
  position: absolute;
  top: 5px;
  right: 5px;
  cursor: pointer;
}

.card_body {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.block_title {
  font-size: 16px;
  margin: 16px 0;
}

.info_header {
  display: flex;
  align-items: center;
}

.info_header > div {
  margin-right: 5px;
  background-color: #f8f8f8;
}

.info_block {
  width: 300px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  border: 1px solid #e5e6eb;
  flex-shrink: 0;
}

.info_block1 {
  width: 300px;
  height: 40px;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  border: 1px solid #e5e6eb;
  flex-shrink: 0;
}

.info_block1 > div:hover {
  background-color: #efefef;
}

.info_block1 > div:nth-child(1) {
  width: 200px;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  border-right: 1px solid #e5e6eb;
}

.info_block1 > div:nth-child(2) {
  width: 100px;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.info_body {
  display: flex;
  align-items: center;
}

.info_body:hover .info_block,
.info_body:hover .info_block1 {
  border-bottom-color: #6186ca;
}

.info_body > div {
  margin-right: 5px;
  background-color: #fff;
  border-top: 0;
}
</style>
